package models

import (
	"github.com/astaxie/beego/orm"
	"strings"
	"errors"
)

type TBasicInfo struct {
	Id    int64  `orm:"column(id);auto" description:""  form:"id"  json:"id"`
	System int   `orm:"column(system)" description:"基础平台"  form:"system"  json:"system"`
	Type  string `orm:"column(type);size(45);null" description:"基础信息类型"  form:"type"  json:"type"`
	Value string `orm:"column(value);size(45);null" description:"基础信息值"  form:"value"  json:"value"`
}

func (t *TBasicInfo) TableName() string {
	return "t_basic_info"
}

func init() {
	orm.RegisterModel(new(TBasicInfo))
}

func GetAllTBasicInfo(query map[string]interface{}, fields []string, sortby []string, order []string,
offset int64, limit int64, needCount bool) (ml []TBasicInfo, totalCount int64, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(TBasicInfo))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, 0, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, 0, errors.New("Error: unused 'order' fields")
		}
	}

	//开始查询构建
	var l []TBasicInfo
	qs = qs.OrderBy(sortFields...)
	if needCount == true {
		if totalCount, err = qs.Count(); err != nil {
			return nil, 0, err
		}
	}
	if limit > 0 {
		qs = qs.Limit(limit, offset)
	}else {
		qs = qs.Limit(50000) //beego orm 默认1000, 为获取全部数据需要设置一个大一点的值
	}
	if _, err = qs.All(&l); err == nil {
		return l, totalCount, nil
	}
	return nil, totalCount, err
}

//获取所有基础类型
func GetAllType() (ml []TBasicInfo, err error)  {
	o := orm.NewOrm()
	qs := o.QueryTable(new(TBasicInfo))

	var l []TBasicInfo
	_, err = qs.Distinct().All(&l, "type") //去掉重复

	return l, err
}
//根据类型获取该类型的所有值
func GetValuesByType(typ string) (t []TBasicInfo, err error)   {
	o := orm.NewOrm()
	qs := o.QueryTable(new(TBasicInfo)).Filter("type", typ)
	_, err = qs.Distinct().All(&t) //去掉重复
	return
}


// AddTBasicInfo insert a new TBasicInfo into database and returns
// last inserted Id on success.
func AddTBasicInfo(m *TBasicInfo) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}
// UpdateTBasicInfoById updates TBasicInfo by Id and returns error if
// the record to be updated doesn't exist
func UpdateTBasicInfoById(m *TBasicInfo) (vo *TBasicInfo, err error) {
	o := orm.NewOrm()
	v := TBasicInfo{Id: m.Id}
	if _, err = o.Update(m); err == nil {
		return m, nil

	}
	return &v, nil
}

func DeleteTBasicInfoById(id int64) (num int64, err error) {
	o := orm.NewOrm()
	num, err = o.Delete(&TBasicInfo{Id: id})
	return
}